package com.jlb.base.interceptor;

import com.jlb.core.enums.SessionEnum;
import com.jlb.core.exceptions.BaseException;
import com.jlb.setting.service.SessionSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LoginInterceptor
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private SessionSV sessionSV;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader(SessionEnum.Authorization.name());

        //TODO 测试接口使用，发布项目时删掉
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(SessionEnum.Authorization.name());
        }
        if (StringUtils.isBlank(token)) {
            throw new BaseException(BaseException.BaseExceptionEnum.Session_Error);
        }

        if (StringUtils.isNotBlank(token)) {
            token = this.sessionSV.refresh(token);//刷新token
            response.addHeader(SessionEnum.Token.name(), token);
            return true;
        }


        boolean flag = true;

        //未登录需要跳转的地址
        String loginUri = "/page/login";
        //如果是ajax请求响应头会有，x-requested-with
        if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Location", loginUri);    //跳转登陆页面
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}